package org.jeecg.modules.htxincailiao.analytics.controller;

import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.contant.HTClient;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.IPInfo;
import org.jeecg.common.util.IPUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.analytics.domain.dto.HTNewsDetailVisitUpdateDTO;
import org.jeecg.modules.htxincailiao.analytics.domain.vo.HTNewsDetailVisitInfoVO;
import org.jeecg.modules.htxincailiao.analytics.domain.vo.HTNewsDetailVisitStatisticsVO;
import org.jeecg.modules.htxincailiao.analytics.entity.HTNewsDetailVisitAction;
import org.jeecg.modules.htxincailiao.analytics.entity.HTNewsDetailVisitAction;
import org.jeecg.modules.htxincailiao.analytics.service.IHTNewsDetailVisitActionService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.htxincailiao.area.entity.HTArea;
import org.jeecg.modules.htxincailiao.area.service.IHTAreaService;
import org.jeecg.modules.htxincailiao.news.entity.HTNews;
import org.jeecg.modules.htxincailiao.news.service.IHTNewsService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: ht_news_detail_visit_action
 * @Author: jeecg-boot
 * @Date: 2022-12-10 10:12:02
 * @Version: V1.0
 */
@Api(tags = "ht_news_detail_visit_action")
@RestController
@RequestMapping("/analytics/hTNewsDetailVisitAction")
@Slf4j
public class HTNewsDetailVisitActionController extends JeecgController<HTNewsDetailVisitAction, IHTNewsDetailVisitActionService> {
    @Resource
    private IHTNewsDetailVisitActionService hTNewsDetailVisitActionService;

    @Resource
    private IHTNewsService newsService;

    @Resource
    private IHTAccountService accountService;

    @Resource
    private IHTAreaService areaService;

    /**
     * PV、UV数据查询
     *
     * @param req
     * @param beginTime
     * @param endTime
     * @return
     */
    @AutoLog(value = "ht_news_detail_visit_action-分页列表查询")
    @ApiOperation(value = "ht_newsDetail_visit_action-分页列表查询", notes = "ht_news_detail_visit_action-分页列表查询")
    @GetMapping(value = "/getPVUVData")
    public Result<?> getPVUVData(HttpServletRequest req, String beginTime, String endTime) {
        List<HTNewsDetailVisitInfoVO> list = hTNewsDetailVisitActionService.getPVUVData(beginTime, endTime);
        return Result.OK(list);
    }

    /**
     * PV、UV数据查询
     *
     * @param req
     * @param beginTime
     * @param endTime
     * @return
     */
    @AutoLog(value = "ht_newsDetail_visit_action-分页列表查询")
    @ApiOperation(value = "ht_news_detail_visit_action-分页列表查询", notes = "ht_news_detail_visit_action-分页列表查询")
    @GetMapping(value = "/getStatistics")
    public Result<?> getStatistics(HttpServletRequest req, String beginTime, String endTime) {
        HTNewsDetailVisitStatisticsVO vo = hTNewsDetailVisitActionService.getStatistics(beginTime, endTime);
        return Result.OK(JSONObject.parse(JSONObject.toJSONString(vo)));
    }


    /**
     * 分页列表查询
     *
     * @param hTNewsDetailVisitAction
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ht_news_detail_visit_action-分页列表查询")
    @ApiOperation(value = "ht_news_detail_visit_action-分页列表查询", notes = "ht_news_detail_visit_action-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HTNewsDetailVisitAction hTNewsDetailVisitAction,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HTNewsDetailVisitAction> queryWrapper = QueryGenerator.initQueryWrapper(hTNewsDetailVisitAction, req.getParameterMap());
        Page<HTNewsDetailVisitAction> page = new Page<HTNewsDetailVisitAction>(pageNo, pageSize);
        IPage<HTNewsDetailVisitAction> pageList = hTNewsDetailVisitActionService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param hTNewsDetailVisitAction
     * @return
     */
    @AutoLog(value = "ht_news_detail_visit_action-添加")
    @ApiOperation(value = "ht_news_detail_visit_action-添加", notes = "ht_news_detail_visit_action-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody HTNewsDetailVisitAction hTNewsDetailVisitAction, HttpServletRequest req) {
        if (oConvertUtils.isEmpty(hTNewsDetailVisitAction.getNewsId())) {
            return Result.error("新闻ID不能为空");
        }
        String ip = IPUtil.getClientIp(req);
//        String ip = "182.149.201.158";
        IPInfo info = null;
        try {
            info = IPUtil.getIPInfo(ip);
        } catch (Exception e) {
        }

        if (oConvertUtils.isNotEmpty(ip)) {
            hTNewsDetailVisitAction.setVisitIp(ip);
        }

        Result<JSONObject> result = new Result<>();
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = null;
        if (oConvertUtils.isNotEmpty(token)) {
            username = JwtUtil.getUsername(token);
        }

        if (oConvertUtils.isNotEmpty(hTNewsDetailVisitAction.getClientOsString())) {
            Integer clientOs = HTClient.GetClientOsIndex(hTNewsDetailVisitAction.getClientOsString());
            hTNewsDetailVisitAction.setClientOs(clientOs);
        }

        HTPlatformUser user = null;
        if (oConvertUtils.isNotEmpty(username)) {
            user = accountService.queryFrontendUserByUsername(username);
        }

        if (oConvertUtils.isNotEmpty(user)) {
            hTNewsDetailVisitAction.setUserId(user.getId());
        }

        String provinceName = oConvertUtils.isNotEmpty(info) ? info.getProvinceName() : null;
        if (oConvertUtils.isNotEmpty(provinceName)) {
            List<HTArea> list = areaService.queryByName(provinceName);
            if (!list.isEmpty()) {
                HTArea area = list.stream().findFirst().orElse(null);
                if (oConvertUtils.isNotEmpty(area)) {
                    hTNewsDetailVisitAction.setProvinceId(area.getId());
                }
            }
        }
        String provinceId = hTNewsDetailVisitAction.getProvinceId();
        if (oConvertUtils.isNotEmpty(provinceId)) {
            List<HTArea> list = areaService.fuzzyQueryByName(provinceName);
            if (!list.isEmpty()) {
                HTArea area = list.stream().findFirst().orElse(null);
                if (oConvertUtils.isNotEmpty(area)) {
                    hTNewsDetailVisitAction.setProvinceId(area.getId());
                }
            }
        }

        if (hTNewsDetailVisitActionService.save(hTNewsDetailVisitAction)) {
            HTNews news = newsService.getById(hTNewsDetailVisitAction.getNewsId());
            Integer clickCount = news.getClickCount() + 1;
            news.setClickCount(clickCount);
            newsService.updateById(news);

            HTNewsDetailVisitAction action =
                    hTNewsDetailVisitActionService.getById(hTNewsDetailVisitAction.getId());
            JSONObject obj = new JSONObject();
            obj.put("visitInfo", action);
            result.setResult(obj);
        } else {
            result.error500("保存访问日志失败");
        }

        return Result.OK("添加成功!");
    }


    /**
     * 编辑
     *
     * @param body 请求参数
     * @return
     */
    @AutoLog(value = "ht_news_detail_visit_action-编辑")
    @ApiOperation(value = "ht_news_detail_visit_action-编辑", notes = "ht_news_detail_visit_action-编辑")
    @RequestMapping(value = "/visitEdit", method = {RequestMethod.POST})
    public Result<?> visitEdit(HttpServletRequest request, @RequestBody String body) throws IOException {
        HTNewsDetailVisitUpdateDTO dto = JSONObject.parseObject(body, HTNewsDetailVisitUpdateDTO.class);
        if (oConvertUtils.isNotEmpty(dto.getId())) {
            HTNewsDetailVisitAction htNewsDetailVisitAction = hTNewsDetailVisitActionService.getById(dto.getId());
            //  只更新需要更新的数据即可
            if (oConvertUtils.isNotEmpty(dto.getLeaveTime())) {
                htNewsDetailVisitAction.setLeaveTime(dto.getLeaveTime());
                hTNewsDetailVisitActionService.updateById(htNewsDetailVisitAction);
            }
        }

        return Result.OK("编辑成功!");
    }

    /**
     * 编辑
     *
     * @param hTNewsDetailVisitAction
     * @return
     */
    @AutoLog(value = "ht_news_detail_visit_action-编辑")
    @ApiOperation(value = "ht_news_detail_visit_action-编辑", notes = "ht_news_detail_visit_action-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HTNewsDetailVisitAction hTNewsDetailVisitAction) {
        hTNewsDetailVisitActionService.updateById(hTNewsDetailVisitAction);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_news_detail_visit_action-通过id删除")
    @ApiOperation(value = "ht_news_detail_visit_action-通过id删除", notes = "ht_news_detail_visit_action-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        hTNewsDetailVisitActionService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ht_news_detail_visit_action-批量删除")
    @ApiOperation(value = "ht_news_detail_visit_action-批量删除", notes = "ht_news_detail_visit_action-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hTNewsDetailVisitActionService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ht_news_detail_visit_action-通过id查询")
    @ApiOperation(value = "ht_news_detail_visit_action-通过id查询", notes = "ht_news_detail_visit_action-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HTNewsDetailVisitAction hTNewsDetailVisitAction = hTNewsDetailVisitActionService.getById(id);
        if (hTNewsDetailVisitAction == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hTNewsDetailVisitAction);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hTNewsDetailVisitAction
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HTNewsDetailVisitAction hTNewsDetailVisitAction) {
        return super.exportXls(request, hTNewsDetailVisitAction, HTNewsDetailVisitAction.class, "ht_news_detail_visit_action");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HTNewsDetailVisitAction.class);
    }

}
